package Lab.Lab2;

import java.io.*;
import java.util.Scanner;

/**
 * @Description:学生类的成员变量包括姓名（字符串）、院系（字符串）、年龄（整型）和平均成绩（实型）
 * 输入1个学生的信息，创建学生对象，使用数据流将该对象的各个成员变量保存到文件中，然后再从文件中读取并显示学生信息。
 * @Author:AMark
 * @Date: 10/30/2023
 */
public class Student {
    private String name, faculty;
    private int age;
    private double grade;
    //空的构造函数
    public Student(){

    }
    //构造函数创建学生类对象
    public Student(String name, String faculty, int age, double grade) {
        this.name = name;
        this.faculty = faculty;
        this.age = age;
        this.grade = grade;
    }
    String getName() {
        return name;
    }
    String getFaculty() {
        return faculty;
    }
    int getAge() {
        return age;
    }
    double getGrade() {
        return grade;
    }
}
class test{
    public static void main(String[] args) {
        Student[] stu = new Student[5];
        Scanner sc = new Scanner(System.in);
        DataInputStream dis = null;
        DataOutputStream dos = null;
        try{
            dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("E:\\Obsidian\\CS\\CS Code\\Java\\learning-java\\IOStream\\src\\Lab\\Lab2\\students.txt")));
            System.out.println("请输入学生姓名、学院、年龄、成绩：");
            for (int i = 0; i < 3; i++) {
                stu[i] = new Student(sc.next(), sc.next(), sc.nextInt(), sc.nextDouble());
                dos.writeUTF(stu[i].getName());
                dos.writeUTF(stu[i].getFaculty());
                dos.writeInt(stu[i].getAge());
                dos.writeDouble(stu[i].getGrade());
            }
            dos.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件打不开！");
        } catch (IOException e) {
            System.out.println("文件写入失败！");
        }
        try {
            //创建文件输入流，缓冲输入流和数据输入流
            dis = new DataInputStream(new BufferedInputStream(new FileInputStream("E:\\Obsidian\\CS\\CS Code\\Java\\learning-java\\IOStream\\src\\Lab\\Lab2\\students.txt")));
            System.out.println("文件中的内容：");
            System.out.println("姓名 学院 年龄 成绩");
            for (int i = 0; i < 3; i++) {
                System.out.print(dis.readUTF() + " ");
                System.out.print(dis.readUTF() + " ");
                System.out.print(dis.readInt() + " ");
                System.out.println(dis.readDouble() + " ");
            }
            dis.close();
        } catch (FileNotFoundException e) {
            System.out.println("没有找到文件！");
        } catch (IOException e) {
            System.out.println("文件读取错误！");
        }
    }
}
